package InternetTcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-10-11
 * Time: 17:01
 */
public class TcpEchoClient {
    //1：创建一个Scoket对象
    private Socket socket = null;
    //2：构造方法因为 TCP是有连接的 所以Scoket对象中包含服务器的IP和端口,实例化对象就会与服务器创立连接，服务器中的accept就会进行呼应
    public TcpEchoClient(String serverIp , int serverPort) throws IOException {
        socket = new Socket(serverIp , serverPort);
    }
    public void start(){
        System.out.println("客户端启动");
        //一：获取控制台输入
        //3:基于socket文件创建输入输出流，并实例化两个扫描器
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scannerConsole = new Scanner(System.in);//控制台扫描器
            Scanner scannerNetWork = new Scanner(inputStream);
            //5:调用PrintWriter中的write方法发送请求,用outputStream帮助构造
            PrintWriter writer = new PrintWriter(outputStream);

            while(true){
                System.out.print("->");
                if (!scannerConsole.hasNext()){
                    break;
                }
                //二：构造请求，并发送
                String request = scannerConsole.next();
                writer.println(request);//呼应server中的获取响应scanner.next()//问题
                writer.flush();
                //三：接收响应
                String response = scannerNetWork.next();
                //四：在显示器上进行打印
                System.out.println(response);


            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
